import requests
from lxml import etree
from wget import bar_adaptive, bar_thermometer, download
import time
import ctypes

urlBase = "https://bing.ioliu.cn/"

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36'
}


def getImgeUrl(urlBase, page):
    url = urlBase+"?p="+str(page)
    response = requests.get(url=url, headers=headers)
    time.sleep(1)
    if response.status_code == 200:
        html = etree.HTML(response.text)
        imageUrlList = html.xpath(
            '//img[@class="progressive__img progressive--not-loaded"]/@src')
        
        return imageUrlList


def downRangeUrl(startPage, endPage):
    print("小主,代码开始执行了喔")
    while startPage < endPage:
        imageUrlList = getImgeUrl(urlBase=urlBase, page=startPage)
        print('现在开始为您下载第{0}页...'.format(startPage))
        startPage += 1
        downloadImage(imageUrlList=imageUrlList)


def downloadImage(imageUrlList):
    savePath = "D://image/必应/"
    print("将为您保存在%s" % {savePath})
    for url in imageUrlList:
        url = url.replace('640', '1920').replace('480', '1080')
        download(url, out=savePath, bar=bar_adaptive)
    # with open('bizhi.html','w+',encoding='utf-8') as f:
    #     f.write(response.text)

def menu():
    print("###########################欢迎来到自动下载壁纸系统#########################")
    print("#                                                                       #")
    print("#                                 -   -                                 #")
    print("#                                   √                                   #")
    print("#  ⚪ tips:                                                             #")
    print("#  ⚪ 1.当前仅支持必应网站(未来会扩展)                                    #")
    print("#  ⚪ 2.当前支持输入页码下载(未来会扩展)                                  #")
    print("#########################################################################")
    page=input("请输入您想下载的页码数量:")
    return page
if __name__ == "__main__":
    # 获取图片url
    # page=1
    # while(page<10):
    #     getImgeUrl(urlBase=urlBase,page=page)
    #     page+=1
    downRangeUrl(1,int(menu()))
